<?php

//power by wshoto.com
if (!defined('IN_IA')) {
    die( 'Access Denied' );
}

class Ewei_DShop_Order {
    function getDispatchPrice($weight, $d){
        if (empty( $d )) {
            return 0;
        }
        $price = 0;
        if ($weight <= $d['firstweight']) {
            $price = intval($d['firstprice']);
        } else {
            $price = intval($d['firstprice']);
            $secondweight = $weight - intval($d['firstweight']);
            $dsecondweight = intval($d['secondweight']) <= 0 ? 1 : intval($d['secondweight']);
            $secondprice = 0;
            if ($secondweight % $dsecondweight == 0) {
                $secondprice = $secondweight / $dsecondweight * intval($d['secondprice']);
            } else {
                $secondprice = ( (int)( $secondweight / $dsecondweight ) + 1 ) * intval($d['secondprice']);
            }
            $price += $secondprice;
        }
        return $price;
    }

    public function payResult($params){
        global $_W;
        $fee = intval($params['fee']);
        $data = array( 'status' => $params['result'] == 'success' ? 1 : 0 );
        $ordersn = $params['tid'];
        $order = pdo_fetch('select id,openid,ordersn,price,openid,dispatchtype,addressid,carrier,status,isverify,deductcredit2 from ' . tablename('ewei_shop_order') . ' where  ordersn=:ordersn and uniacid=:uniacid limit 1', array( ':uniacid' => $_W['uniacid'], ':ordersn' => $ordersn ));
        $orderid = $order['id'];
        if ($params['from'] == 'return') {
            $address = false;
            if (empty( $order['dispatchtype'] )) {
                $address = pdo_fetch('select realname,mobile,address from ' . tablename('ewei_shop_member_address') . ' where id=:id limit 1', array( ':id' => $order['addressid'] ));
            }
            $carrier = false;
            if ($order['dispatchtype'] == 1) {
                $carrier = unserialize($order['carrier']);
            }
            if ($params['type'] == 'cash') {
                show_json(2, array( 'order' => $order, 'address' => $address, 'carrier' => $carrier ));
            } else {
                if ($order['status'] == 0) {

                    if ($params['type'] == 'credit') {
                        $payquery = true;
                    } else if ($params['type'] == 'wechat') {
                        $payquery = m('finance')->isWeixinPay($order['ordersn'], $params['fee'] * 100);
                    } else {
                        show_json(0, '仅支持余额支付与微信支付');
                        exit();
                    }

                    if(!is_error($payquery)){
                        pdo_update('ewei_shop_order', array( 'status' => 1, 'paytime' => time() ), array( 'id' => $orderid ));

                        if ($order['deductcredit2'] > 0) {
                            $shopset = m('common')->getSysset('shop');
                            m('member')->setCredit($order['openid'], 'credit2', -$order['deductcredit2'], array( 0, $shopset['name'] . "余额抵扣: {$order['deductcredit2']} 订单号: " . $order['ordersn'] ));
                        }

                        $this->setStocksAndCredits($orderid, 1);
                        $url = "./index.php?i={$_W['uniacid']}&c=entry&m=ewei_shop&do=order&t=detail&id={$orderid}";
                        m('notice')->sendOrderMessage($orderid);

                        // 等级商品购买，改变用户等级
                        //$this->changeLevel($order['id'], $order['openid']);

                        if (p('commission')) {
                            p('commission')->checkOrderPay($order['id']);
                        }
				//20161016更新
                         } else {
                        show_json(0, $payquery);
                    }

                }
			//20161016更新
 $isnotifyphp = $params['isnotifyphp'];
                if($isnotifyphp=='zhanglingzhiJswsWlkj'){
                    $result = array(
                        'return_code' => 'SUCCESS',
                        'return_msg' => 'OK'
                    );
                    echo array2xml($result);
                    exit();
		    }
                show_json(1, array( 'order' => $order, 'address' => $address, 'carrier' => $carrier ));
            }
        }
    }

    private function changeLevel($orderid, $openid){
        global $_W;

        if(!empty($orderid) && $openid){
            $sql = 'SELECT `goodsid` FROM '.tablename('ewei_shop_order_goods').' WHERE `uniacid` = :uniacid AND `orderid` = :orderid LIMIT 1';
            $par = array(':uniacid' => $_W['uniacid'], ':orderid' => $orderid);
            $goodsid = pdo_fetchcolumn($sql, $par);

            $sql = 'SELECT `type`,`changelevel` FROM '.tablename('ewei_shop_goods').' WHERE `uniacid` = :uniacid AND `id` = :id LIMIT 1';
            $par = array(':uniacid' => $_W['uniacid'], ':id' => $goodsid);
            $result = pdo_fetch($sql, $par);

            if($result['type'] == 3 && $result['changelevel'] != 0){
                $status = pdo_update('ewei_shop_member', array('level' => $result['changelevel']), array('openid' => $openid));

                if($status !== false){
                    pdo_update('ewei_shop_order', array( 'status' => 3, 'finishtime' => time() ), array( 'id' => $orderid ));
                }

                logging_run(array('update' => $status), 'changeLevel');
            }
        }

        return true;
    }

    /**
     * 获取当月用户消费金额
     * @param $openid
     * @return float
     */
    public function getMonthAmount($openid){
        global $_W;

        $stime = date('Y-m-01', strtotime(date("Y-m-d")));
        $etime = strtotime(date('Y-m-d', strtotime("$stime +1 month -1 day")));
        $stime = strtotime($stime);

        $sql = 'SELECT sum(price) as total FROM '.tablename('ewei_shop_order').' WHERE `uniacid` = :uniacid AND `openid` = :openid AND `status` = 3 AND `finishtime` >= :stime AND `finishtime` <= :etime';
        $par = array(':uniacid' => $_W['uniacid'], ':openid' => $openid, ':stime' => $stime, ':etime' => $etime);
        $result = pdo_fetch($sql, $par);

        return floatval($result['total']);
    }

    /**
     * 获取指定用户消费总金额
     * @param $openid
     * @return float
     */
    public function getAllAmount($openid){
        global $_W;

        $sql = 'SELECT sum(goodsprice) as total FROM '.tablename('ewei_shop_order').' WHERE `uniacid` = :uniacid AND `openid` = :openid AND `status` = 3';
        $par = array(':uniacid' => $_W['uniacid'], ':openid' => $openid);
        $result = pdo_fetch($sql, $par);

        return floatval($result['total']);
    }

    function setStocksAndCredits($orderid = '', $type = 0){
        global $_W;
        $order = pdo_fetch('select id,price,openid,dispatchtype,addressid,carrier,status from ' . tablename('ewei_shop_order') . ' where id=:id limit 1', array( ':id' => $orderid ));
        $goods = pdo_fetchall("select og.goodsid,og.total,g.totalcnf,g.credit,og.optionid,g.total as goodstotal,og.optionid,g.sales,g.salesreal from " . tablename('ewei_shop_order_goods') . " og " . " left join " . tablename('ewei_shop_goods') . " g on g.id=og.goodsid " . " where og.orderid=:orderid and og.uniacid=:uniacid ", array( ':uniacid' => $_W['uniacid'], ':orderid' => $orderid ));
        $credits = 0;
        foreach ($goods as $g) {
            $stocktype = 0;
            if ($type == 0) {
                if ($g['totalcnf'] == 0) {
                    $stocktype = -1;
                }
            } else {
                if ($type == 1) {
                    if ($g['totalcnf'] == 1) {
                        $stocktype = -1;
                    }
                } else {
                    if ($type == 2) {
                        if ($order['status'] >= 1) {
                            if ($g['totalcnf'] == 1) {
                                $stocktype = 1;
                            }
                        } else {
                            if ($g['totalcnf'] == 0) {
                                $stocktype = 1;
                            }
                        }
                    }
                }
            }
            if (!empty( $stocktype )) {
                if (!empty( $g['optionid'] )) {
                    $option = m('goods')->getOption($g['goodsid'], $g['optionid']);
                    if (!empty( $option ) && $option['stock'] != -1) {
                        $stock = -1;
                        if ($stocktype == 1) {
                            $stock = $option['stock'] + $g['total'];
                        } else {
                            if ($stocktype == -1) {
                                $stock = $option['stock'] - $g['total'];
                                $stock <= 0 && ( $stock = 0 );
                            }
                        }
                        if ($stock != -1) {
                            pdo_update('ewei_shop_goods_option', array( 'stock' => $stock ), array( 'uniacid' => $_W['uniacid'], 'goodsid' => $g['goodsid'], 'id' => $g['optionid'] ));
                        }
                    }
                }
                if (!empty( $g['goodstotal'] ) && $g['goodstotal'] != -1) {
                    $totalstock = -1;
                    if ($stocktype == 1) {
                        $totalstock = $g['goodstotal'] + $g['total'];
                    } else {
                        if ($stocktype == -1) {
                            $totalstock = $g['goodstotal'] - $g['total'];
                            $totalstock <= 0 && ( $totalstock = 0 );
                        }
                    }
                    if ($totalstock != -1) {
                        pdo_update('ewei_shop_goods', array( 'total' => $totalstock ), array( 'uniacid' => $_W['uniacid'], 'id' => $g['goodsid'] ));
                    }
                }
            }
            $credits += $g['credit'] * $g['total'];
            if ($type == 0) {
                pdo_update('ewei_shop_goods', array( 'sales' => $g['sales'] + $g['total'] ), array( 'uniacid' => $_W['uniacid'], 'id' => $g['goodsid'] ));
            } elseif ($type == 1) {
                if ($order['status'] >= 1) {
                    pdo_update('ewei_shop_goods', array( 'salesreal' => $g['salesreal'] + $g['total'] ), array( 'uniacid' => $_W['uniacid'], 'id' => $g['goodsid'] ));
                }
            }
        }
        $shopset = m('common')->getSysset('shop');
        if ($type == 1) {
            m('member')->setCredit($order['openid'], 'credit1', $credits, array( 0, $shopset['name'] . '购物积分 订单号: ' . $order['ordersn'] ));
        } elseif ($type == 2) {
            if ($order['status'] >= 1) {
                m('member')->setCredit($order['openid'], 'credit1', -$credits, array( 0, $shopset['name'] . '购物取消订单扣除积分 订单号: ' . $order['ordersn'] ));
            }
        }
    }

    public function getOrderByAgentid($agentid){
        global $_W;

        $result = $sql = $pam =  '';

        if(!is_array($agentid) && intval($agentid) != 0){
            $sql = 'SELECT * FROM '.tablename('ewei_shop_order').' WHERE `agentid` = :agentid AND `status` >= 0 AND `uniacid` = :uniacid';
            $pam = array(':uniacid' => $_W['uniacid'], ':agentid' => $agentid);
        }

        if(is_array($agentid)){
            $sql = 'SELECT * FROM '.tablename('ewei_shop_order').' WHERE `agentid` IN ( '.implode(',' , array_keys($agentid)).' ) AND `status` >= 0 AND `uniacid` = :uniacid';
            $pam = array(':uniacid' => $_W['uniacid']);
        }

        return pdo_fetchall($sql, $pam, 'id');
    }

    public function getOrderGoods($oid){
        global $_W;

        $result = $sql = '';

        if(!empty($oid)){
            $sql = 'SELECT * FROM '.tablename('ewei_shop_order_goods').' WHERE `uniacid` = :uniacid ';
            $pam = array(':uniacid' => $_W['uniacid']);

            // 单条
            if(intval($oid) != 0 && !is_array($oid)){
                $pam[':oid'] = $oid;
                $sql .= ' AND `orderid` = :oid ';
            }

            // 多条
            if(is_array($oid)){
                $sql .= ' AND `orderid` in ('. implode(',', $oid) .')';
            }

            $sql .= ' ORDER BY `createtime` DESC ';

            return pdo_fetchall($sql, $pam, 'id');
        }

        return false;
    }

    public function getStatus($status){
        // -1取消状态，0普通状态，1为已付款，2为已发货，3为成功
        $result = '';

        switch($status){
            case -1 :
                $result =  '已取消';
                break;
            case 0 :
                $result =  '已下单';
                break;
            case 1 :
                $result =  '已付款';
                break;
            case 2 :
                $result =  '已发货';
                break;
            case 3 :
                $result =  '已完成';
                break;
            default :
                $result =  '错误';
                break;
        }

        return $result;
    }

    /**
     * 获取指定的商品数据
     * @param int $orderid
     * @return array|bool
     */
    public function getGoodsByOrderId($orderid = 0){
        global $_W;

        if (empty( $orderid )) {
            return false;
        }

        $goodsFeild = 'og.*, g.hascommission, g.commission1_rate, g.commission1_pay, g.commission2_rate, g.commission2_pay, g.commission3_rate, g.commission3_pay';
        $goodsSql = ' select ' . $goodsFeild . ' from ' . tablename('ewei_shop_order_goods') . ' as og ';
        $goodsSql .= ' left join ' . tablename('ewei_shop_goods') . ' as g on g.id = og.goodsid ';
        $goodsSql .= ' where og.orderid=:orderid and og.uniacid=:uniacid';

        return pdo_fetchall($goodsSql, array( ':orderid' => $orderid, ':uniacid' => $_W['uniacid'] ));
    }

    /**
     * 获取指定订单的详细信息
     * @param  $orderid
     * @return array|bool
     */
    public function getOrderInfo($orderid, $field = array()){
        global $_W;

        if (empty( $orderid )) {
            return false;
        }

        if (!empty( $field )) {
            $tmep = '';

            $count = count($field);

            for ($i = 0; $i < $count; $i++) {
                if ($i == 0) {
                    $tmep .= ' `' . $field[$i] . '` ';
                } else {
                    $tmep .= ', `' . $field[$i] . '` ';
                }
            }

            $field = $tmep;
        } else {
            $field = '*';
        }

        if (is_array($orderid)) {
            $sql = 'SELECT ' . $field . ' FROM ' . tablename('ewei_shop_order') . ' WHERE `uniacid` = :uniacid AND `id` IN ( ' . implode(',', $orderid) . ' ) ORDER BY `createtime` DESC ';
            return pdo_fetchall($sql, array( ':uniacid' => $_W['uniacid'] ));
        } else {
            $sql = 'SELECT ' . $field . ' FROM ' . tablename('ewei_shop_order') . ' WHERE `uniacid` = :uniacid AND `id` = :orderid ';
            return pdo_fetch($sql, array( ':uniacid' => $_W['uniacid'], ':orderid' => $orderid ));
        }
    }

    /**
     * 获取指定用户，指定状态的订单统计数据。
     * @param $openid
     * @param array $options
     * @return bool | array
     */
    public function getOrderStatistics($openid, $options = array()){
        global $_W;

        if (empty( $openid )) {
            return false;
        }

        $member = m('member')->getMember($openid);

        if(empty($member)){
            return false;
        }

        $result = array();

        if(in_array('ordersum', $options)){
            $sql  = 'SELECT SUM(og.realprice) AS ordersum FROM ' . tablename('ewei_shop_order') . ' o ' ;
            $sql .= ' LEFT JOIN  ' . tablename('ewei_shop_order_goods') . ' og ON og.orderid = o.id ' ;
            $sql .= ' WHERE o.openid = :openid AND o.status = :status AND o.uniacid = :uniacid LIMIT 1';

            $parm = array(':uniacid' => $_W['uniacid'], ':openid' => $openid, ':status' => 3);

            $result['ordersum'] =  pdo_fetchcolumn($sql, $parm);
        }

        if(in_array('ordercount', $options)){
            $sql  = 'SELECT COUNT(DISTINCT o.id) AS ordersum FROM ' . tablename('ewei_shop_order') . ' o ' ;
            $sql .= ' LEFT JOIN  ' . tablename('ewei_shop_order_goods') . ' og ON og.orderid = o.id ' ;
            $sql .= ' WHERE o.openid = :openid AND o.status = :status AND o.uniacid = :uniacid LIMIT 1';

            $parm = array(':uniacid' => $_W['uniacid'], ':openid' => $openid, ':status' => 3);

            $result['ordercount'] =  pdo_fetchcolumn($sql, $parm);
        }

        if(in_array('agentordersum', $options)){
            $sql = 'SELECT SUM(cg_money) FROM '.tablename('ewei_shop_commission_record').' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = :status ';
            $parm = array(':uniacid' => $_W['uniacid'], ':mid' => $member['id'], ':status' => 3);

            $result['agentordersum'] =  pdo_fetchcolumn($sql, $parm);
        }

        if(in_array('agentordercount', $options)){
            $sql = 'SELECT COUNT(DISTINCT orderid) FROM '.tablename('ewei_shop_commission_record').' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = :status ';
            $parm = array(':uniacid' => $_W['uniacid'], ':mid' => $member['id'], ':status' => 3);

            $result['agentordercount'] =  pdo_fetchcolumn($sql, $parm);
        }

        if(in_array('agent1ordersum', $options)){
            $sql = 'SELECT SUM(cg_money) FROM '.tablename('ewei_shop_commission_record').' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = :status AND `c_rank` = :rank ';
            $parm = array(':uniacid' => $_W['uniacid'], ':mid' => $member['id'], ':status' => 3, ':rank' => 1);

            $result['agent1ordersum'] =  pdo_fetchcolumn($sql, $parm);
        }

        if(in_array('agent1ordercount', $options)){
            $sql = 'SELECT COUNT(DISTINCT orderid) FROM '.tablename('ewei_shop_commission_record').' WHERE `uniacid` = :uniacid AND `mid` = :mid AND `o_status` = :status AND `c_rank` = :rank ';
            $parm = array(':uniacid' => $_W['uniacid'], ':mid' => $member['id'], ':status' => 3, ':rank' => 1);

            $result['agent1ordercount'] =  pdo_fetchcolumn($sql, $parm);
        }

        return $result;
    }
}